package constellation.custom;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

import androidx.annotation.Nullable;

@SuppressLint("AppCompatCustomView")
public class CircleImageView2 extends ImageView {

    // 声明圆形的半径
    int mRadius;
    Paint mPaint;
    float scale;  //得到图片缩放的比例

    public CircleImageView2(Context context) {
        super(context);
    }

    public CircleImageView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int height = getMeasuredHeight();
        int width = getMeasuredWidth();
        //因为要形成圆形，先画正方形，圆形是正方形的内切圆。
        int size = Math.min(height, width);
        mRadius = size / 2;
        setMeasuredDimension(size, size);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        mPaint = new Paint();
        Drawable drawable = getDrawable();   //获取显示的图片对象
        if (drawable != null) {
            Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();  //将图片对象转换成位图对象
//            进行图片平铺的渲染
            BitmapShader bitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
            scale = (mRadius * 2.0f) / Math.min(bitmap.getHeight(), bitmap.getWidth());

            Matrix matrix = new Matrix();
            matrix.setScale(scale, scale);
            bitmapShader.setLocalMatrix(matrix);
            mPaint.setShader(bitmapShader);

//            绘制圆形
            canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);
        } else {
            super.onDraw(canvas);
        }
    }
}
